package com.gjx.clock.service

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.widget.Toast
import com.gjx.clock.AlarmHelper
import com.gjx.clock.ClockApplication
import com.gjx.clock.TimeFormatHelper
import com.gjx.clock.dao.RestClockSettingDao
import com.gjx.clock.ui.AlarmActivity
import java.util.*

class RestService : Service() {
    companion object{
        val START_WORKING = "START_WORKING"
        val STOP_WORKING = "STOP_WORKING"
        val CANCEL = "CANCEL"
    }



    val am by lazy {
        getSystemService(Context.ALARM_SERVICE) as AlarmManager
    }

    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        val restClock = RestClockSettingDao.getSavedClock()

        val manager = getSystemService("statusbar")
        val clazz = Class.forName("android.app.StatusBarManager")
        val collapse = clazz.getMethod("collapsePanels")
        collapse.isAccessible=true
        collapse.invoke(manager)

        val action = intent?.action
        when(action){
            START_WORKING -> {
                AlarmHelper.cancelRestAlarm(this,false)
                AlarmHelper.setRestAlarm(this,restClock.workingTime,true,RestService.START_WORKING)
            }
            STOP_WORKING ->{
                AlarmHelper.cancelRestAlarm(this,false)
                AlarmHelper.setRestAlarm(this,restClock.restTime,true,RestService.STOP_WORKING)
            }
            CANCEL->{
                AlarmHelper.cancelRestAlarm(this,true)
            }
        }

        return super.onStartCommand(intent, flags, startId)
    }

    private fun addOneAlarm(triggerAtMillis:Long,requestCode:Long,notify:Boolean) {
        if(notify) {
            Toast.makeText(this, "闹钟将在${TimeFormatHelper.timeFormat(triggerAtMillis)}开启", Toast.LENGTH_SHORT).show()
        }
        // 响铃的activity
        val intent = Intent(this, AlarmActivity::class.java)
        intent.putExtra("lastTime", Date().time)
        intent.putExtra("triggerAtMillis",triggerAtMillis)
        intent.putExtra("requestCode", requestCode)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        val pi = PendingIntent.getActivity(this, requestCode.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
        am.setExactAndAllowWhileIdle(
            AlarmManager.RTC_WAKEUP,
            triggerAtMillis,
            pi
        )
    }

    private fun cancelAlarm(requestCode:Long,notify:Boolean){

        val intent = Intent(this, AlarmActivity::class.java)
        val pi = PendingIntent.getActivity(this, requestCode.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
        am.cancel(pi)
        if(notify){
            Toast.makeText(this, "取消了闹钟", Toast.LENGTH_SHORT).show()
        }
    }
}
